/*
 * XbEvent.h
 *
 *  Created on: Dec 31, 2009
 *      Author: evaleto
 */

#ifndef XBEVENT_H_
#define XBEVENT_H_

#include <inttypes.h>

class XbLiteReader;

#define SEC_ELAPSED		5000L		//each      5'000 [ms]
#define MIN_ELAPSED		60000L		//each     60'000 [ms]
#define HOUR_ELAPSED	3600000L	//each  3'600'000 [ms]
#define DAY_ELAPSED	   86400000L	//each 86'400'000 [ms]

//define anchor
#define SEC  0
#define MIN  1
#define HOUR 2
#define DAY  3



/**
 *
 */
class XbEvent {
public:
	XbEvent();
	~XbEvent();

	/**
	 * compute power and log wh
	 * power is determined by the time (s) between two pulses
	 * 1) 1kwh  8000 pulses => 1 pulse == 0.125 wh
	 * 2) time x between two pulse == 0.125 wh
	 * 3) 0.125 wh *3600/3600 == 450 ws
	 * 4) x(s) = 450ws => [s]=[ws] => 450/x=[w]
	 */
	void onReceiveData(XbLiteReader &xb);
	void onError(XbLiteReader &xb);

protected:
	bool managecache(uint8_t slice, uint8_t max, uint32_t ms);
	uint16_t avg(uint16_t buffer[], uint8_t len);
	// log and return the power
	uint16_t logpower( uint32_t ms);
	uint16_t computePower(uint32_t pulses, uint32_t intime);
	uint16_t power; 		//current power
	uint32_t pulses;		//current pulses
	uint32_t time;		//current millis (ulong ~ 50 days)

	// saved buffer contains type of time
	uint8_t  buffertype;
	uint16_t bufferpower[60];
	uint8_t  bufferpowersize;



};

#endif /* XBEVENT_H_ */
